
Morik.Office.CompanyPanel = function(config) {

	Morik.Office.CompanyPanel.superclass.constructor.call(this, config);

	var proxy = new Ext.ux.data.DWRProxy( {
		dwrFn : CompanyManager.getCompanys
	});

	var recordType = new Ext.data.Record.create([ {
		name : "id",
		type : "int"
	}, {
		name : "comNum",
		type : "string"
	}, {
		name : "comName",
		type : "string"
	}, {
		name : "comAddress",
		type : "string"
	}]);

	// 定义分析器
	var reader = new Ext.data.JsonReader( {
		totalProperty : "totalSize",
		root : "data",
		id : "id"
	}, recordType);

	// 定义store
	var ds = new Ext.data.Store( {
		proxy : proxy,
		reader : reader,
		pruneModifiedRecords : true
	});
	this.ds = ds;
	// 第二，讲一下cm,grid
	// ds or data

	var myData = [[3300, "test0"], [3301, "test1"], [3302, "test2"],
			[3303, "test3"], [3304, "test4"], [3305, "test5"], [3306, "test6"],
			[3307, "test7"], [3308, "test8"]];

	var store1 = new Ext.data.SimpleStore( {
		fields : [ {
			name : 'value',
			type : 'string'
		}, {
			name : 'name',
			type : 'string'
		}]
	});
	store1.loadData(myData);
	var test = new Ext.form.ComboBox( {
		tpl : '<tpl for="."><div ext:qtip="{name}" class="x-combo-list-item">{name}</div></tpl>',
		store : store1,
		displayField : 'name',
		valueField : 'value',
		typeAhead : true,
		triggerAction : 'all',
		mode : 'local',
		emptyText : '请选择...',
		selectOnFocus : true,
		loadingText : 'loading....'
	});
	var conv = new Ext.ux.RelativeRender( {
		ds : store1,
		header : '编号',
		dataIndex : 'comNum',
		editor : test
	});

	var cm = new Ext.grid.ColumnModel( {
		defaultSortable : true,
		defaultWidth : 180,
		columns : [conv, {
			header : '名称',
			dataIndex : 'comName',
			editor : new Ext.form.TextField( {
				width : 180,
				allowBlank : false
			})
		}, {
			header : '公司地址',
			width : 300,
			dataIndex : 'comAddress',
			editor : new Ext.form.TextField( {
				width : 180,
				allowBlank : false
			})
		}]
	});

	var callback = function(r) {
		if (ds._button)
			ds._button.enable();
	};
	var exception = function(r) {
		if (ds._button)
			ds._button.enable();
	};
	var update = function(t, r, type) {
		if (type == Ext.data.Record.COMMIT) {
			CompanyManager.saveCompany(r.data, {
				callback : callback,
				exceptionHandler : exception
			});
		}
	};
	var remove = function(t, r, i) {
		CompanyManager.removeCompany(r.data);
	};

	ds.on( {
		'update' : update,
		'remove' : remove
	});

	var buttonSave = new Ext.Button( {
		text : '保存',
		handler : function(e) {
			this.disable();
			ds._button = this;
			ds.commitChanges();
		}
	});
	var buttonReset = new Ext.Button( {
		text : '复位',
		handler : function() {
			this.disable();
			ds._button = this;
			ds.rejectChanges();
		}
	});
	var buttonDelete = new Ext.Button( {
		text : '删除',
		handler : function(e) {
			this.disable();
			ds._button = this;
			var d = function(btn, text) {
				var sm = grid.getSelectionModel()
				if (btn == 'yes') {
					var rec = sm.getSelected();
					if (!rec)
						return;
					ds.remove(rec);
				}
			}
			Ext.MessageBox.confirm("确定删除", "是否真的要删除？", d);
		}
	});
	var t = this;
	var buttonNew = new Ext.Button( {
		text : '新加',
		handler : function(e) {
			this.disable();
			var sm = grid.getSelectionModel();
			var rec = sm.getSelected();
			if (!rec)
				rec = ds.getAt(0);
			var c = rec.copy();
			c.data['_mark'] = 'add';
			c.data['id'] = 1000;
			var s = new (recordType)(Ext.apply(c.data, config || {}));
			ds.insert(0, [s]);
			grid.stopEditing();
			grid.startEditing(0, 1);
			this.enable();
			// t.pagingBar.updateInfo();
		}
	});

	var pagingBar = new Ext.PagingToolbar( {
		pageSize : 10,
		store : ds,
		displayInfo : true,
		displayMsg : '共有 {2}，当前显示 {0} - {1}条',
		emptyMsg : "没有数据",
		items : ['-', buttonSave, '-', buttonDelete, '-', buttonNew, '-',
				buttonReset]
	});
	this.pagingBar = pagingBar;
	//var sm = new Ext.grid.RowSelectionModel();

	var grid = new Ext.grid.EditorGridPanel( {
		cm : cm,
		//sm : sm,
		store : ds,
		width : 660,
		height : 400,
		bbar : pagingBar,
		loadMask : {
			msg : '正在载入数据,请稍等...'
		},
		title : '公司列表'
	});
	// ds.load();
   // store1.on('load',function(){grid.refresh()};
	this.add(grid);
	// 第三、调整，tbar分页,工具栏

}
Ext.extend(Morik.Office.CompanyPanel, Ext.Panel);





Morik.Office.CompanyPanel = function(config) {	
	Morik.Office.CompanyPanel.superclass.constructor.call(this, config);
	var proxy = new Ext.ux.data.DWRProxy( {
		dwrFn : CompanyManager.getCompanys});
	var recordType = new Ext.data.Record.create([]);
	var reader = new Ext.data.JsonReader( {}, recordType);
	var ds = new Ext.data.Store( {
		proxy : proxy,
		reader : reader,
		pruneModifiedRecords : true
	});
	this.ds = ds;	
	var mp=this;
    ds.on("metachange",function(d,m){
       if(m&&Ext.isArray(m.fields)){
       	var f=m.fields,_heads=[];      
         for(var i=0;i<f.length;i++){
         	if(!f[i]._head){continue;}
         	 var o={};
         	 o.header=f[i]._head;
         	 o.dataIndex=f[i].name;
         	 o.editor= new Ext.form.TextField( {});
			_heads.push(o);
         	}               
       }
     mp.grid.getColumnModel().setConfig(_heads);	   
    });	
	var cm = new Ext.grid.ColumnModel( {
		defaultSortable : true});
   
	var callback=function(r){
		if(ds._button)
	  ds._button.enable();		
	   };
	var	exception= function(r){
	  if(ds._button)
	  ds._button.enable();
	    };
	var update = function(t, r, type) {
		if (type == Ext.data.Record.COMMIT) {
			CompanyManager.saveCompany(r.data,{callback:callback,exceptionHandler:exception});
		}
	};
	var remove = function(t, r, i) {
		CompanyManager.removeCompany(r.data);
	};
	ds.on( {
		'update' : update,
		'remove' : remove
	});

	var buttonSave = new Ext.Button( {
		text : '保存',
		handler : function(e) {
			this.disable();
			ds._button=this;
			ds.commitChanges();
		}
	});
	var buttonReset = new Ext.Button( {
		text : '复位',
		handler : function(e) {
			//mp.showForm(e);
			 this.disable();
		 ds._button=this;
			 ds.rejectChanges();
		}
	});
	var buttonDelete = new Ext.Button( {
		text : '删除',
		handler : function(e) {
			this.disable();
			ds._button=this;
			var d = function(btn, text) {
				var sm= grid.getSelectionModel()
				if (btn == 'yes')
				var rec =sm.getSelected();
			   if (!rec) return ;				
					ds.remove(rec);
			}
			Ext.MessageBox.confirm("确定删除", "是否真的要删除？", d);
		}
	});
    var t=this;
	var buttonNew = new Ext.Button( {
		text : '新加',
		handler : function(e) {
			this.disable();
			var sm= grid.getSelectionModel();
			var rec=sm.getSelected();
			if (!rec)
				rec = ds.getAt(0);
			var c = rec.copy();			
			// c.data['_mark'] = 'add';
			c.data['id']=1000;			
			var s = new (recordType)(Ext.apply(c.data, config || {}));
			ds.insert(0,[s]);
			// if(!ds._addRec) ds._addRec=[];
			// ds._addRec.push(s);
			if(!ds.modified)ds.modified=[];
			ds.modified.push(s);
			grid.stopEditing();			
			grid.startEditing(0, 1);
			this.enable();
		// t.pagingBar.updateInfo();
		}
	});

	var pagingBar = new Ext.PagingToolbar( {
		pageSize : 10,
		store : ds,
		displayInfo : true,
		displayMsg : '共有 {2}，当前显示 {0} - {1}条',
		emptyMsg : "没有数据",
		items : ['-', buttonSave, '-', buttonDelete, '-', buttonNew, '-',
				buttonReset]
	});
	this.pagingBar=pagingBar;
	var sm = new Ext.grid.CheckboxSelectionModel();
// var sm =Ext.grid.CheckboxSelectionModel();
	var grid = new Ext.grid.EditorGridPanel( {
		cm : cm,
		sm : new Ext.grid.CheckboxSelectionModel(),
		store : ds,
		width : 600,
		height : 300,
		bbar : pagingBar,
		loadMask : {
			msg : '正在载入数据,请稍等...'
		},
		title : '公司列表'
	});
	this.grid=grid;
	this.add(grid);
}
Ext.extend(Morik.Office.CompanyPanel, Ext.Panel,{
 showForm:function(e){
 	var t=this;
 	var arr=['.tw{border-top-width:0px}',
		        '.bw{border-bottom-width:0px}',
		        '.lw{border-left-width:0px}',
		        '.rw{border-right-width:0px}',
		        '.bor{border:none;border-collapse: collapse}',
		        ' #otc td{height:22px; text-align:center; vertical-align:middle; }',
		        ' #otc td.bgan{ text-align:left!important}',
		        '#otc table .gb23{font-family:"楷体_GB2312",Verdana, Arial, Helvetica, sans-serif; font-size:13px;}',
		        '.hdbd{ width:100%;heigth:100%;text-align:center; background:transparent;border:0px;}'];
	var str=arr.join(' ');
	Ext.util.CSS.createStyleSheet(str);
      // this.addRule(arr);
  var win;
	if (!win) {
		win = new Ext.Window( {
			modal : true,		
			width : 650,		
			autoHeight:true,
			closeAction : 'hide',
			modal:true,
			constrainHeader:true,
			plain:true,
			title:'OTC个性渠道促销申请表' ,
			hidden:true	,
			buttonAlign :'center',
			buttons:[{text:'提交',handler:Ext.emptyFn()},{text:'复位'}]
		});
	}
	win.on('render',function(){		
       this.body.load({url:'otc.txt?data='+new Date(), scripts: true,callback:function(){
       win.show();
       t.calcu();        
       }}); },win);
	win.render(Ext.getBody());
	
    /* 因为采用autoheigth,所以开始位置是中间，但是load数据之后就不在中间 */
},
addRule:function(s){
 if(Ext.isArray(s)){
    for(var i=0;i<s.length;i++){
      this.addRule(s[i]);
       }
 }else{
  var index=document.styleSheets[0].cssRules.length||1; 
   document.styleSheets[0].insertRule(s, index);
    }
  },
  calcu:function(){   
    var sc=Ext.get('shopcount');
    var sp=Ext.get('shopper');
    var cs= Ext.get('covercount');// scope
    var ev=function(){    	
    	var scv=parseFloat(sc.dom.value);
    	var spv=parseFloat(sp.dom.value)/100; 
    	var csv=parseFloat(cs.dom.value);
      if (!isNaN(scv)&&!isNaN(spv)&&!isNaN(csv)) {      	
      	var v1=Math.round(((csv-scv)/scv)*100*100)/100;
      	var v2=Math.round((csv/(scv/spv))*100*100)/100;
        Ext.get('coveraddper').dom.value=v1;
        Ext.get('coverper').dom.value=v2;
        } 
    }
    if(cs)  cs.on('blur',ev,this);
    if(sc)  sc.on('blur',ev,this);
    if(sp)  sp.on('blur',ev,this);
    
    
    var salec=Ext.get('salecount');
    var psalcec=Ext.get('plansalecount');
    var psalep=Ext.get('plansaleaddper');    
    var ex=function(){
      var scv=salec.getValue(true);
      var pscv=psalcec.getValue(true);    
       if (!isNaN(scv)&&!isNaN(pscv))  {  
         	var v1=Math.round(((pscv-scv)/scv)*100*100)/100;
            psalep.dom.value=v1;
           }
      }
    if(salec) salec.on('blur',ex,this);
    if(psalcec)psalcec.on('blur',ex,this);
    
    
    var ed=function(){
      var d2= this.child('td:nth-child(2)');
      var d3= this.child('td:nth-child(3)');
      var d4= this.child('td:nth-child(4)');
      var ret=parseFloat(Ext.getDom('returnMoney').value);
      var oth=parseFloat(Ext.getDom('otherMoney').value);      
      var v2=parseFloat(d2.dom.value);
      var v3=d3.getValue(true); 
      if (!isNaN(v2)&&!isNaN(v3))  {  
        var v1=Math.round(v2*v3*100)/100;
         d4.dom.value=v1;
         var all= Ext.select('#retgds tr:not(#retgds tr:nth(1)) td:nth-child(4)',true);
         var v=0;
         all.each(function(){
          if(this.value){
          	var va=parseFloat(this.value);
            if (!isNaN(va))v=v+va;
           }            
         });         
         if(!isNaN(ret))v=v+ret;
         if(!isNaN(oth))v=v+oth;
         
         Ext.getDom('totalMoney').value=v;
         
        }
       };
     
  var rowFirst= Ext.DomQuery.selectNode('#retgds tr:nth(2)');
  var n1=rowFirst.child('td:first-child ');
  rowFirst.child('td:nth-child(2)').on('blur',ed,rowFirst);
  rowFirst.child('td:nth-child(3)').on('blur',ed,rowFirst);
  
   
 
  var ec=function(){
    var str='<tr id=>'+
               ' <td class="lw bw"> <input type="text" class="gb23 hdbd"  />  </td>'+
               ' <td  class="bw"> <input type="text" class="gb23 hdbd"  /> </td>'+
                '<td  class="bw"> <input type="text" class="gb23 hdbd"  /> </td>'+
                '<td  class="bw"><input type="text"  readonly="readonly"  class="gb23 hdbd"  /> </td>'+
                '<td  class="bw rw"><input type="text" class="gb23 hdbd" /> </td>'+
              '</tr>';
    var newRow= Ext.DomHelper.append(Ext.get("retgds"),str,true);    
     n1.un('blur',ec); 
     newRow.child('td:first-child ').on('blur',ev,newRow);
     newRow.child('td:nth-child(2)').on('blur',ed,newRow);
     newRow.child('td:nth-child(3)').on('blur',ed,newRow);
       
  }
  n1.on('blur',ec);
   
  }
});



